package org.sbear.service.impl;

import com.sun.mail.smtp.SMTPAddressFailedException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.sbear.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * 电子邮件服务impl
 *
 * @author xxyWi
 * @date 2021/02/05
 */
@Service
public class EmailServiceImpl implements EmailService {

    private static Logger log = LogManager.getLogger(EmailServiceImpl.class);

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;

    private static final String EMAIL_SUBJECT = "注册验证码";

    @Override
    public boolean email(String email, String code) {
        System.out.println("email被调用到啦，email=" + email);

        String text = "您的验证码为：  " + code + "\r\n不要告诉别人哟";

        try {
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper mimeMessageHelper = null;
            mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            mimeMessageHelper.setFrom(new InternetAddress("作业<" + from + ">"));
            mimeMessageHelper.setTo(email);
            mimeMessageHelper.setSubject(EMAIL_SUBJECT);
            mimeMessageHelper.setText(text, true);

            // 发送邮件
            mailSender.send(mimeMessage);
        } catch (SMTPAddressFailedException e) {
            log.error("邮件发送失败，邮箱地址错误，检查邮箱输入是否有误 ex={}", e.getMessage(), e);
            return false;
        } catch (MessagingException e) {
            log.error("邮件发送失败 ex={}", e.getMessage(), e);
            return false;
        }

        log.info("邮件发送成功");
        return true;
    }
}
